#!/usr/bin/env python
# -*- coding: utf-8 -*-

import Singleton
import xml.dom.minidom



@Singleton.singleton
class Data(object):
    def __init__(self):
        self.ReadXmlData()

    def get(self, key):
        try:
            key = key.split('.')
            res = self.MarketCuring[key[0]]
            for i in range(1, len(key)):
                res = res[key[i]]
            return res
        except:
            return None

    def ReadXmlData(self):
        dom = xml.dom.minidom.parse('./config.xml')
        root = dom.documentElement

        self.MarketCuring = {}
        ret = root.getElementsByTagName('Start')
        for i in ret:
            self.MarketCuring[i.getAttribute('type')] = {
                u'mode': i.getAttribute('mode'),
                u'ResetDataBase': (i.getAttribute('ResetDataBase') == "True"),
                u'LogTimeInterval': i.getAttribute('LogTimeInterval')
            }

        ret = root.getElementsByTagName('Robot')
        for i in ret:
            self.MarketCuring[u'Robot'] = {
                u'ip': i.getAttribute('ip'),
                u'port': i.getAttribute('port')
            }

        ret = root.getElementsByTagName('PreMkt')
        for i in ret:
            self.MarketCuring[u'PreMkt'] = {
                u'ip': i.getAttribute('ip'),
                u'port': i.getAttribute('port')
            }

        ret = root.getElementsByTagName('StockServer')
        for i in ret:
            self.MarketCuring[u'StockServer'] = {
                u'ip': i.getAttribute('ip'),
                u'port': i.getAttribute('port')
            }

        db = {}
        ret = root.getElementsByTagName('MarketSource')
        for i in ret:
            db[i.getAttribute("type")] = {
                "ip": i.getAttribute("ip"),
                "port": int(i.getAttribute("port"))
            }
        self.MarketCuring['market'] = db

if __name__ == "__main__":
    test = Data()
    print test.get("Start.mode")
    print test.get("Robot.ip")